# -*- coding:utf-8 -*-
import os
import random
import re
import string
import uuid
import inspect


def check_url_format(url):
    """
    校验url格式是否正确
    :param url: 服务器地址
    :return: bool
    """
    if re.match("^https?://[\\w\\-_\\d]+(\\.[\\w\\-_\\d]+)+(:\\d{1,5})?$", url):
        return True
    else:
        return False


def check_mobile_format(mobile):
    """
    校验手机号格式是否正确
    :param mobile: 手机号
    :return: bool
    """
    if re.match("1[3456789]\\d{9}", mobile):
        return True
    else:
        return False


def random_character(cType: str = "str", length: int = 4):
    """
    生成随机字符
    :param cType: 类型  枚举值：{"str": 大小写字母加数字, "int": 数字}
    :param length: 需要生成的字符长度
    :return: str
    """
    if cType == "str":
        chr_all = string.ascii_letters + string.digits
    elif cType == "int":
        chr_all = string.digits
    else:
        raise TypeError("类型不正确，只支持str和int")
    try:
        length = int(length)
    except Exception as e:
        return TypeError("length格式有误")

    try:
        ret = "".join(random.sample(chr_all, length))
    except ValueError:
        ret = "".join(random.choice(chr_all) for _ in range(length))
    return ret


def random_uuid():
    return uuid.uuid4()


def del_file(dirPath, pattern: list):
    """
    删除不需要的文件
    :param dirPath: 目录
    :param pattern: 规则
    """
    for file in list(os.walk(os.path.join(os.getcwd(), dirPath)))[0][-1]:
        if any(file.endswith(pat) for pat in pattern) or any(file.startswith(pat) for pat in pattern):
            os.remove(os.path.join(os.getcwd(), file))


resultDict = {}


def cache():
    return resultDict


def set_cache(server_addr, user_addr, method_name):
    """增加执行记录，用于查询造数据脚本执行情况"""
    if user_addr not in resultDict.keys():
        resultDict[user_addr] = {}
    if server_addr not in resultDict.get(user_addr).keys():
        resultDict[user_addr][server_addr] = {}
    if method_name not in resultDict.get(user_addr).get(server_addr).keys():
        resultDict[user_addr][server_addr][method_name] = 0
    resultDict[user_addr][server_addr][method_name] += 1


def clear_cache(user_addr, server_addr):
    """清除执行记录，释放内存"""
    try:
        del resultDict[user_addr][server_addr]
    except Exception as e:
        pass
    if not resultDict.get(user_addr):
        try:
            del resultDict[user_addr]
        except:
            pass


def get_func_name():
    """获取当前方法名称"""
    return inspect.stack()[1][3]


if __name__ == '__main__':
    r = check_url_format("https://192.168.2.53:8080")
    print(r)
